<!-- 部门配置 -->
<template>
  <div>
    <el-row style="background: #fff;">
      <div class="top topSubmitBtn">
        <el-button class="btn" type="primary" @click="addDepartment()" >添加角色</el-button>
      </div>
      <div>
        <el-table 
          border 
          :data="tableData" 
          style="width: 100%; margin: 15px 0" 
          row-key="ID"  
          default-expand-all 
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column prop="date" type="index" label="序号" width="80" ></el-table-column>
          <el-table-column prop="Role" label="角色名称" width="150" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Right" label="角色权限" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.Right ? row.Right.join(',') : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Inner" label="内置角色" width="100" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.Inner === 1 ? '否' : '是' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Descp" label="角色备注" width="250" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" fixed="right" width="180px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.Inner !== 1">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.Inner !== 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-dialog
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape=false
      :title="Action === 1 ? '添加角色' : '修改角色'"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="600px">
      <el-form label-width="100px" :model="departForm" :rules="rules" ref="departForm">
        <el-form-item label='角色名称:' prop="Role">
          <el-input v-model.trim="departForm.Role" :disabled="Action === 2 ? true : false" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label='角色备注:' prop="Descp">
          <el-input v-model.trim="departForm.Descp" type="textarea" :rows="2" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label='角色权限:' prop="Right">
          <el-tree
            ref="tree"
            :data="roleList"
            v-model="departForm.Right"
            accordion
            show-checkbox
            node-key="permission"
            :default-checked-keys="['首页']"
            :props="{ multiple: true, label:'permission', value: 'permission' }">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { connrequest } from "@/api/firstPage";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  computed: {
    ...mapGetters([
      'permission_routes',
    ]),
  },
  data() {
    return {
      dialogVisible: false,
      Action: 1,
      departForm:{},
      roleList:[],
      tableData: [],
      rules:{
        Role: [
          { required: true, message: '角色名称不能为空' }
        ]
      }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    async getData(){
      const res = await connrequest('GetUserRole')
      this.handelRouter()
      this.tableData = res.Data
    },
    handelRouter(){
      let arr = this.permission_routes.filter(item => item.meta && item.meta.title && item.meta.title !== 'errorPages')
      this.roleList = [...arr]
    },
    handleChange(row){
    },
    addDepartment(){
      this.Action = 1
      this.departForm = {}
      this.$nextTick(()=>{
        this.$refs['departForm'].clearValidate()
        this.$refs.tree.setCheckedKeys(['首页']);
      })
      this.dialogVisible = true
    },
    handleEdit(item){
      if(item.Inner === 0){
        this.$message.error('该角色为内置角色，禁止修改')
        return false
      }
      this.Action = 2
      this.departForm = { ...item }
      this.$nextTick(()=>{
        this.$refs.tree.setCheckedKeys(this.departForm.Right);
      })
      this.dialogVisible = true
    },
    async submit(){
      let arr = [...this.tableData]
      this.$refs['departForm'].validate( async(valid) => {
        if(valid){
          let RightList = [...new Set(this.$refs.tree.getCheckedKeys())]
          if(this.Action === 1){
            if(this.tableData.findIndex(role => role.Role === this.departForm.Role) !== -1){
              this.$message.error('该角色名称已经存在')
              return false
            }
            arr.push( 
              {
                Inner: 1, 
                Role: this.departForm.Role,
                Right: RightList,
                Descp: this.departForm.Descp,
              } 
            )
          }else if(this.Action === 2){
            arr.forEach(item => {
              if(item.Role === this.departForm.Role){
                item.Inner = this.departForm.Inner 
                item.Role = this.departForm.Role
                item.Right = RightList
                item.Descp = this.departForm.Descp
              }
              return item
            })
          }
          const data = { 
            Data:[...arr]
          }
          const res = await connrequest('SetUserRole', data)
          if(res.Status.StatusCode === 0){
            this.$message({
              type: 'success',
              message: this.Action === 1 ? '角色添加成功' : '角色修改成功'
            });
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    async handleDelete(item){
      if(item.Inner === 0){
        this.$message.error('该角色为内置角色，禁止删除')
        return false
      }
      const res = await connrequest('GetUserInfo')
      let UserList = res.Data
      if(UserList.findIndex(user => user.Role === item.Role) !== -1){
        this.$message.error('该角色已被用户使用，禁止删除')
        return false
      }
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let arr = this.tableData.filter(deleteItem => deleteItem.Role !== item.Role)
        let data = {
          Data:arr
        }
        const res = await connrequest('SetUserRole', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>